@page "/movies/delete"
@using Microsoft.EntityFrameworkCore
@using BlazorWebAppMovies.Models
@inject IDbContextFactory<BlazorWebAppMovies.Data.BlazorWebAppMoviesContext> DbFactory
@inject NavigationManager NavigationManager

<PageTitle>Delete</PageTitle>

<h1>Delete</h1>

<p>Are you sure you want to delete this?</p>
<div>
    <h2>Movie</h2>
    <hr />
    @if (movie is null)
    {
        <p><em>Loading...</em></p>
    }
    else {
        <dl class="row">
            <dt class="col-sm-2">Title</dt>
            <dd class="col-sm-10">@movie.Title</dd>
        </dl>
        <dl class="row">
            <dt class="col-sm-2">Release Date</dt>
            <dd class="col-sm-10">@movie.ReleaseDate</dd>
        </dl>
        <dl class="row">
            <dt class="col-sm-2">Genre</dt>
            <dd class="col-sm-10">@movie.Genre</dd>
        </dl>
        <dl class="row">
            <dt class="col-sm-2">Price</dt>
            <dd class="col-sm-10">@movie.Price</dd>
        </dl>
        <dl class="row">
            <dt class="col-sm-2">Rating</dt>
            <dd class="col-sm-10">@movie.Rating</dd>
        </dl>
        <EditForm method="post" Model="movie" OnValidSubmit="DeleteMovie" FormName="delete" Enhance>
            <button type="submit" class="btn btn-danger" disabled="@(movie is null)">Delete</button> |
            <a href="/movies">Back to List</a>
        </EditForm>
    }
</div>

@code {
    private Movie? movie;

    [SupplyParameterFromQuery]
    private int Id { get; set; }

    protected override async Task OnInitializedAsync()
    {
        using var context = DbFactory.CreateDbContext();
        movie = await context.Movie.FirstOrDefaultAsync(m => m.Id == Id);

        if (movie is null)
        {
            NavigationManager.NavigateTo("notfound");
        }
    }

    private async Task DeleteMovie()
    {
        using var context = DbFactory.CreateDbContext();
        context.Movie.Remove(movie!);
        await context.SaveChangesAsync();
        NavigationManager.NavigateTo("/movies");
    }
}
